package ua.eug.airv1.map;

import java.util.Random;

import ua.eug.airv1.ImageProvider;
import ua.eug.airv1.controllers.ScreenController;
import ua.eug.airv1.utils.Config;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Touchable;

public class MapHolder extends Group implements IOnScreen {
	private Tile map[][];
	
	protected MapHolder() {
		super();
				
		map = new Tile[Config.SIZEX][Config.SIZEY];
		for( int i = 0; i<Config.SIZEX; i++) {
			for (int j = 0;j<Config.SIZEY;j++) {
				map[i][j] = Tile.ZTile;
			}
		}
		
		ScreenController.getInstance().addSlave(this);
	}
	
	private static class SingletonHolder {
        public static final MapHolder HOLDER = new MapHolder();
    }
	
	public static MapHolder getInstance() {
        return SingletonHolder.HOLDER;
    }

	// TODO load from file
	public void loadMap() {
		Random randomGenerator = new Random();
		MapListener mapListener = new MapListener();
		
		map = new Tile[Config.SIZEX][Config.SIZEY];
		for( int i = 0; i<Config.SIZEX; i++) {
			for (int j = 0;j<Config.SIZEY;j++) {
				int segments[] = {0,0,0};
				
				// TODO connector
				for (int k = 0; k < 3; k++)
					segments[k] = randomGenerator.nextInt(ImageProvider.NLANDS);
				
				Tile t = new Tile(segments);
				map[i][j] = t;
				t.pos = new TilePos(i,j);
				
				if (j>20)
					t.setFogOfWar(true);
				
				Vector2 p = ScreenController.getInstance().XyToStage(i,j);
				
				if (j>0 && !(i==0 && j%2==0) && j<Config.SIZEY-1 && !(i==Config.SIZEX -1 && j%2==1)) { // non-border tiles
					t.setName("["+i+","+j+"]");
					t.setTouchable(Touchable.enabled);
					t.setBounds(Config.TileBorderX,Config.TileBorderY,
							Config.TileWidth-Config.TileBorderX,
							Config.TileHeight-Config.TileBorderY);
					t.addListener(mapListener);
				} else {
					t.disabled = true;
				}
				t.setPosition(p.x, p.y);
				addActor(t);
			}
		}
	}
	
	public Tile getTile(int x, int y) {
		return map[x][y];
	}

	@Override
	public void pan(float x, float y) {
		this.setPosition(x, y);
	}
	@Override
	public void zoom(float z) {
		this.setScale(z);
	}
}
